/**
 * 
 */
package info.niwota.ziplock;

import java.io.File;
import java.io.IOException;

import android.os.Environment;

/**
 * @author qiangli
 * 
 */
public final class SDCard {
	private static final String ROOT = "ziplock";

	/**
	 * 
	 */
	private SDCard() {
	}

	private static boolean checkFsWritable() {
		// Create a temporary file to see whether a volume is really writable.
		// It's important not to put it in the root directory which may have a
		// limit on the number of files.
		File dir = getRoot();
		if (dir == null) {
			return false;
		}
		File f = new File(dir, ".probe");
		try {
			if (f.exists()) {
				f.delete();
			}
			if (!f.createNewFile()) {
				return false;
			}
			f.delete();
			return true;
		} catch (IOException e) {
			return false;
		}
	}

	public static boolean hasStorage() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			boolean writable = checkFsWritable();
			return writable;
		}
		return false;
	}

	public static File getRoot() {
		File sdcard = Environment.getExternalStorageDirectory();
		File dir = new File(sdcard, ROOT);
		if (!dir.isDirectory()) {
			if (!dir.mkdirs()) {
				return null;
			}
		}
		return dir;
	}
	
	public static boolean checkSDCard() {
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_REMOVED)
				|| state.equals(Environment.MEDIA_UNMOUNTED)
				|| state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)
				|| state.equals(Environment.MEDIA_UNMOUNTABLE)) {
			return false;
		}
		return true;
	}
}
